package com.eric.demo.netty.ch7;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author ZhangGuangyin on 2018/9/9
 */
public class EchoClientHandler extends ChannelHandlerAdapter {
    private final int sendNumber;

    /**
     * Creates a client-side handler.
     */
    public EchoClientHandler(int sendNumber) {
        this.sendNumber=sendNumber;
    }

    private UserInfo[] UserInfo(){
        UserInfo[] userInfos=new UserInfo[sendNumber];
        UserInfo userInfo=null;
        for(int i=0;i<sendNumber;i++){
            userInfo=new UserInfo();
            userInfo.setUserID(i);
            userInfo.setUserName("ABCDEFG"+i);
            userInfos[i]=userInfo;
        }
        return userInfos;
    }

    private UserInfo UserInfo(int i){
        UserInfo userInfo=new UserInfo();
        userInfo.setUserID(i);
        userInfo.setUserName("ABCDEFG"+i);
        return userInfo;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        UserInfo[] infos=UserInfo();
        for(UserInfo userInfo:infos){
            ctx.write(userInfo);
        }
        ctx.flush();
        /*int i = 0;
        while (i < sendNumber){
            UserInfo userInfo = UserInfo(i++);
            ctx.write(userInfo);
            ctx.flush();
        }*/
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("This is  times from receive server : [" + msg + "]");
        //ctx.writeAndFlush(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
